import nodemailer from "nodemailer";
import getContent from "./mailContext";
import ResultHelper from "../routes/utils/ResultHelper";

// 实例对象
const transporter = nodemailer.createTransport({
  host: "smtp.qq.com",
  port: 465,
  secure: true, // Use `true` for port 465, `false` for all other ports
  auth: {
    user: "914426907@qq.com",
    pass: "ibbyfhylipnhbche",
  },
});

export async function sendMail(
  receiver: string,
  code: string,
  active: string = "验证邮箱"
) {
  const mailOptions = {
    from: '"Flaging 🚩" <taninge@foxmail.com>', // sender address
    to: receiver, // list of receivers
    subject: "【Flaging】邮箱验证码", // 标题
    // text: "Hello world?", // plain text body
    html: getContent(code, active), // html body
  };

  try {
    await transporter.sendMail(mailOptions);

    return ResultHelper.success({}, "发送成功");
  } catch (err) {
    console.error(err);
    if (err.code === "EENVELOPE") {
      return ResultHelper.error("发送的邮箱地址不存在，或其他错误");
    } else {
      return ResultHelper.error(err);
    }
  }
}
